package com.hrm.system.service;

import com.baidu.aip.util.Base64Util;
import com.hrm.common.service.BaseService;
import com.hrm.common.util.IdWorker;
import com.hrm.common.util.QiniuyunUtils;
import com.hrm.domain.company.Department;
import com.hrm.domain.system.Role;
import com.hrm.domain.system.User;
import com.hrm.system.client.DepartmentFeignClient;
import com.hrm.system.dao.RoleDao;
import com.hrm.system.dao.UserDao;
import com.hrm.system.utils.BaiduAiUtil;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

@Service
public class UserService extends BaseService<User> {

    //初始密码
    private static final String INIPASSWORD = "123456";
    //加密迭代次数
    private static final int HASHITERATIONS = 3;
    @Autowired
    private UserDao userDao;
    @Autowired
    private RoleDao roleDao;
    @Autowired
    private IdWorker idWorker;
    @Autowired
    private DepartmentFeignClient departmentFeignClient;
    @Autowired
    private BaiduAiUtil baiduAiUtil;

    /**
     * 保存用户
     */
    public void addUser(User user) {
        String id = idWorker.nextId() + "";
        user.setId(id);
        user.setPassword(new Md5Hash(INIPASSWORD, user.getMobile(), HASHITERATIONS).toString());
        user.setLevel("user");
        user.setEnableState(1);
        userDao.save(user);
    }

    /**
     * 更新用户
     */
    public void updateUser(User user) {
        User temp = userDao.findById(user.getId()).get();
        temp.setUsername(user.getUsername());
        temp.setPassword(user.getPassword());
        temp.setDepartmentId(user.getDepartmentId());
        temp.setDepartmentName(user.getDepartmentName());
        userDao.save(temp);
    }

    /**
     * id查询用户
     */
    public User findUserById(String id) {
        return userDao.findById(id).get();
    }

    /**
     * 查询全部用户列表
     * 参数：map形式：hasDept、departmentId、companyId
     */
    public Page<User> findUsers(Map<String, Object> map, Integer page, Integer size) {
        //1、根据map参数构造可变查询条件
        //2、分页,new PageRequest过时，使用PageRequest.of静态方法，注意page是从0开始，需要-1
        return userDao.findAll(setSpec4User(map), PageRequest.of(page - 1, size));
    }

    /**
     * id删除用户
     */
    public void deleteUser(String id) {
        userDao.deleteById(id);
    }

    /**
     * 分配角色，多对多
     *
     * @param userId
     * @param roleIds
     */
    public void asignRoles(String userId, List<String> roleIds) {
        //查询user
        User user = userDao.findById(userId).get();
        //查询role并封装到set集合中
        Set<Role> roles = new HashSet<>();
        for (String roleId : roleIds) {
            roles.add(roleDao.findById(roleId).get());
        }
        user.setRoles(roles);
        userDao.save(user);
    }

    /**
     * 根据mobile查找
     */
    public User findByMobile(String mobile) {
        return userDao.findByMobile(mobile);
    }

    /**
     * 批量保存新用户
     *
     * @param users
     */
    @Transactional
    public void addUsers(List<User> users, String companyId, String companyName) {
        for (User user : users) {
            user.setId(idWorker.nextId() + "");
            user.setPassword(new Md5Hash("123456", user.getMobile(), 3).toString());
            user.setInServiceStatus(1);
            user.setEnableState(1);
            user.setLevel("user");
            user.setCompanyId(companyId);
            user.setCompanyName(companyName);
            Department department = departmentFeignClient.findByCodeAndCompanyId(user.getDepartmentId(), user.getCompanyId());
            if (department != null) {
                user.setDepartmentId(department.getId());
                user.setDepartmentName(department.getName());
            }
            userDao.save(user);
        }
    }

    /**
     * 用户上传图片
     * base64编码file的byte数组
     * 保存到user
     *
     * @param id
     * @param file
     * @return
     */
    public String uploadImage(String id, MultipartFile file) throws IOException {
        User user = userDao.findById(id).get();
        String s = Base64Util.encode(file.getBytes());
        String dataUrl = "data:image/jpg;base64," + s;
        user.setStaffPhoto(dataUrl);
        userDao.save(user);
        return dataUrl;
    }

    /**
     * 用户上传图片
     * 上传到七牛云存储空间上
     *      重写：上传图片同时传到百度云ai对应用户的人脸库中
     *           判断是否在库中，有则更新，没有则注册
     */
    public String uploadQiniuyun(String id, MultipartFile file) throws IOException {
        User user = userDao.findById(id).get();
        String url = new QiniuyunUtils().uploadQiniuyun(user.getId(), file.getBytes()); //七牛云返回连接
        user.setStaffPhoto(url);
        userDao.save(user);
        //编码base64
        String encode = Base64Util.encode(file.getBytes());
        if (baiduAiUtil.faceExist(user.getId())){
            //存在则更新
            baiduAiUtil.faceUpdate(user.getId(),encode);
        }else {
            //不存在则注册
            baiduAiUtil.faceRegister(user.getId(),encode);
        }
        return url;
    }

}
